package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.auth.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.LImageLoader;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.common.util.RegexUtil;
import com.shundr.auth.frame.constant.LConstants;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.UserInfo;

/**
 * 个人认证提交 AuthOwnnerActivity
 * 
 * @author larry 2015-4-19 下午5:58:39
 * @version 1.0.0
 *
 */
public class AuthOwnnerActivity extends BaseActivity implements OnClickListener {

	private EditText etName;
	private EditText etID;
	private TextView etReason;
	
	private Button btnSubmit;

	private ImageView btnID;

	private PictureInfo mPIDInfo;// 身份证
	
	private UserInfo mUserInfo;

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private int flag = 0;

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.RE_AUTH_DRIVER_SUCCESS:
			case UserRequest.OWNNER_AUTH_COMMIT_SUCCESSED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, "认证提交成功");
				finish();
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, (String) msg.obj);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("mPIDInfo", mPIDInfo);
	};
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		
		mPIDInfo = (PictureInfo) savedInstanceState.getSerializable("mPIDInfo");
		
		if (mPIDInfo != null) {
			ImageLoader.getInstance().displayImage(
					"file://" + mPIDInfo.getFilename(), btnID);
		}
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_auth_ownner);
		
		Intent intent = getIntent();
		mUserInfo = (UserInfo) intent.getSerializableExtra("user");
		
		etName = (EditText) findViewById(R.id.et_name);
		etID = (EditText) findViewById(R.id.et_ID);
		etReason = (TextView) findViewById(R.id.tv_reason);

		btnID = (ImageView) findViewById(R.id.btn_ID);
		btnID.setOnClickListener(this);
		
		btnSubmit = (Button) findViewById(R.id.btn_submit);
		btnSubmit.setOnClickListener(this);

		btnRight.setVisibility(View.VISIBLE);
		btnRight.setText("企业认证");
		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mUserInfo.getIdValidationStatus() == 0 || mUserInfo.getIdValidationStatus() == 3) {
					ToastHelper.toastShort(mContext, "请先提交个人认证，再进行企业认证。");
				} else {
					mContext.startActivity(new Intent(mContext, AuthCompanyActivity.class));
				}
			}
		});
		
		showUserInfo();
	}
	
	private void showUserInfo() {
		if (mUserInfo == null) return;
		
		etName.setText(mUserInfo.getUserName() == null ? "" : mUserInfo.getUserName());
		etID.setText(mUserInfo.getUserCitizenNumber() == null ? "" : mUserInfo.getUserCitizenNumber());
		
		if (!StringUtil.isNullVal(mUserInfo.userCitizenPic)) {
			ImageLoader.getInstance().displayImage(
					mUserInfo.userCitizenPic, btnID);
		}
		// 用户审核中和审核通过之后不能再修改
				if (mUserInfo.getIdValidationStatus() == 1 || mUserInfo.getIdValidationStatus() == 2) {
					etID.setEnabled(false);
					etName.setEnabled(false);
					btnID.setEnabled(false);
				} else {
					etID.setEnabled(true);
					etName.setEnabled(true);
					btnID.setEnabled(true);
					if (mUserInfo.getIdValidationStatus() == 3) {
						etReason.setVisibility(View.VISIBLE);
						etReason.setText(mUserInfo.getIdValidationMsg());
					} else {
						etReason.setVisibility(View.GONE);
					}
				}
	}

	@Override
	protected void onDestroy() {
		releaseImageView(btnID);
		super.onDestroy();
	}

	private boolean check() {
		if (StringUtil.isNull(etName.getText().toString())) {
			etName.requestFocus();
			ToastHelper.toastShort(mContext, "请填写真实姓名");
			return false;
		}
		if (StringUtil.isNull(etID.getText().toString())) {
			etID.requestFocus();
			ToastHelper.toastShort(mContext, "请填写身份证号码");
			return false;
		}

		if (!RegexUtil.CheckIDNum(etID.getText().toString())) {
			etID.requestFocus();
			ToastHelper.toastShort(mContext, "请填写正确的身份证号码");
			return false;
		}

		if ((mUserInfo == null || mUserInfo.getIdValidationStatus() == 0) && mPIDInfo == null) {
			ToastHelper.toastShort(mContext, "请选择身份证件");
			return false;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		String outPic = "";
		if (resultCode == RESULT_OK) {
			try {
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					outPic = PictureUtil.getRealFilePath(mContext, data2);
					outPic = PictureUtil.compressJpgImage(outPic);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					outPic = PictureUtil.compressJpgImage(LConstants.TEMP_PIC_PATH);
					break;
				case PictureUtil.PHOTO_CROP:
					
					break;
				default:
					break;
				}
				
				if (!new File(outPic).exists()) {
					ToastHelper.toastShort(mContext, "选择图片出错，请重新操作！");
					return;
				}
				
				Bitmap bitmap = BitmapFactory.decodeFile(outPic);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(bitmap));
				info.setFilename(outPic);
				bitmap.recycle();
				if (flag == 0) {
					info.setType(PictureInfo.FileType.citizen);
					mPIDInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + outPic, btnID);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1.5);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 600);
			intent.putExtra("outputY", 400);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_ID:
			flag = 0;
			String url;
			
			if (mPIDInfo == null) {
				url = mUserInfo.getUserCitizenPic();
			} else {
				url = "file://" + mPIDInfo.getFilename();
			}
			
			PictureUtil.doPickPhotoAction(mContext, url);
			break;
		case R.id.btn_submit:
			if (check()) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mPIDInfo != null) {
					mPictures.add(mPIDInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				if (mUserInfo != null && mUserInfo.getCompanyValidationStatus() > 0) {
					new UserRequest(mContext, mHandler).commitReAuthOwner(etName
							.getText().toString(), etID.getText().toString(),
							json);
				} else {
					new UserRequest(mContext, mHandler).commitOwnnerAuth(etName
							.getText().toString(), etID.getText().toString(),
							json);
				}
			}
			break;
		default:
			break;
		}
		
	}
}
